//
//  TDModel.m
//  ProjectDemo
//
//  Created by IOS3 on 2019/1/9.
//  Copyright © 2019 IOS3. All rights reserved.
//

#import "TDModel.h"


@interface TDModel ()

@property (nonatomic, strong) NSString *urlString;

@end


@implementation TDModel 
 @synthesize so_downloadProgress, so_downloadState = _so_downloadState, so_downloadError, so_downloadSpeed = _so_downloadSpeed;


- (instancetype)initWithURLString:(NSString *)url {
    self = [self init];
    if (self) {
        self.urlString = url;
        [self checkLocal];
    }
    return self;
}


- (void)checkLocal {
    if ([[NSFileManager defaultManager] fileExistsAtPath:[self savePath]]) {
        self.so_downloadState = SODownloadStateComplete;
//        NSError *error;
//        NSDictionary *fileAttr = [[NSFileManager defaultManager] attributesOfItemAtPath:[self savePath] error:&error];
//        if (!error) {
//            CGFloat size = (CGFloat)([fileAttr fileSize] / 1024.f / 1024);
//            
//        }
    }
}



- (NSString *)savePath {
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSLog(@"document path: %@", docPath);
    
    NSString *saveDir = [docPath stringByAppendingPathComponent:@"local"];
    
    BOOL hasDir = [[NSFileManager defaultManager] fileExistsAtPath:saveDir];
    if (!hasDir) {
        [[NSFileManager defaultManager] createDirectoryAtPath:saveDir withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *fileName = [self.urlString componentsSeparatedByString:@"/"].lastObject;
    NSString *savePath = [saveDir stringByAppendingPathComponent:fileName];
    return savePath;
}






#pragma mark - required 下载地址
- (nonnull NSURL *)so_downloadURL {
    return [NSURL URLWithString:self.urlString];
}


#pragma mark - 判等
- (BOOL)isEqual:(id)object {
    if (![object isKindOfClass:[TDModel class]]) {
        return [super isEqual:object];
    }
    // 如果self和object代表同一个对象，比如这两个对象内存地址不同，但是所有的属性值都相等，对于 SODownloader 来说，就是下载地址相同时返回 YES，否则返回 NO。
    TDModel *model = (TDModel *)object;
    return [self.urlString isEqualToString:model.urlString];
}

/**
 为相等的对象返回相同的hash值，为不相等的对象返回不同的hash值。
 */
- (NSUInteger)hash {
    return [self.urlString hash];
}


@end
